package com.touzhijia.authority.security;

import com.touzhijia.authority.domain.entity.Permission;
import com.touzhijia.authority.domain.entity.User;
import com.touzhijia.authority.mapper.UserMapper;
import com.touzhijia.authority.model.LdapUser;
import com.touzhijia.authority.repository.LdapUserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.query.LdapQuery;
import org.springframework.ldap.query.LdapQueryBuilder;
import org.springframework.security.core.userdetails.UserCache;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.core.userdetails.cache.NullUserCache;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 作者： lzw<br/>
 * 创建时间：2018-03-16 10:54 <br/>
 */
@Component
@Slf4j
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private LdapUserRepository ldapUserRepository;
    @Autowired
    private UserMapper userMapper;

    private UserCache userCache = new NullUserCache();

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("### 开始加载用户信息 [username={}]", username);
        LdapQuery ldapQuery = LdapQueryBuilder.query().filter("(sAMAccountName=" + username + ")");
        LdapUser ldapUser = ldapUserRepository.findOne(ldapQuery);
        if (ldapUser == null) {
            log.info("### 用户不存在LDAP [username={}]", username);
            throw new UsernameNotFoundException("用户不存在");
        }
        // 从本地数据库查询
        User user = userMapper.getByUsername(username);
        if (user == null) {
            log.info("### 用户不存在本地数据库 [username={}]", username);
            throw new UsernameNotFoundException("用户不存在");
        }
        // 获取用户所有角色
        List<Permission> permissionList = userMapper.findAllPermission(username);
        // 获取用所有权限
        CustomUserDetails userDetails = new CustomUserDetails(user);
        for (Permission permission : permissionList) {
            userDetails.getAuthorities().add(new CustomGrantedAuthority(permission));
        }
        return userDetails;
    }
}
